
package com.loan.rebate.common;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件写入，读取工具类
 *
 * @author 朱国军
 * @since 1.0
 * @version 2016年2月16日 朱国军
 */
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    /**
     * closeQuietly
     *
     * @param closeable
     * @throws IOException
     */
    private static void closeQuietly(Closeable closeable) throws IOException {
        if (closeable != null) {
            closeable.close();
        }
    }

    /**
     * InputStream to File
     *
     * @param input the <code>InputStream</code> to read from
     * @param file the File to write
     * @throws IOException
     */
    public static void toFile(InputStream input, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        closeQuietly(os);
        closeQuietly(input);
    }
    
    /**
     * InputStream to File
     *
     * @param input the <code>InputStream</code> to read from
     * @param fullPath 文件全路径，包含文件名和后缀
     * @throws IOException
     */
    public static void toFile(InputStream input, String fullPath) throws IOException {
        
        OutputStream os = new FileOutputStream(createFile(fullPath));
        int bytesRead = 0;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        closeQuietly(os);
        closeQuietly(input);
    }

    /**
     * 创建文件，如果目录不存在则先创建目录,如果存在直接返回文件
     *
     * @param fullPath 文件全路径，包含文件名和后缀
     * @return 创建好目录的文件对象
     */
    public static File createFile(String fullPath) {
        File file = new File(fullPath);

        if (file.exists()) {
            logger.warn("文件已存在，fullPath={}", fullPath);
        } else if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        
        return file;
    }
}
